// API 基础路径
const API_BASE = '/api/v1';

// 对话相关变量
let chatHistory = [];
let currentController = null;

// 添加消息到对话界面
function addMessage(text, role) {
    const messages = document.getElementById('chat-messages');
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${role}-message mb-4 p-4 rounded ${
        role === 'user' ? 'bg-blue-50 ml-12' : 
        role === 'assistant' ? 'bg-gray-50 mr-12' : 
        'bg-yellow-50 text-center'
    }`;
    
    if (role === 'assistant') {
        messageDiv.innerHTML = marked.parse(text);
    } else {
        messageDiv.textContent = text;
    }
    
    messages.appendChild(messageDiv);
    messages.scrollTop = messages.scrollHeight;
}

// 更新最后一条消息
function updateLastMessage(text) {
    const messages = document.getElementById('chat-messages');
    const lastMessage = messages.lastElementChild;
    if (lastMessage && lastMessage.classList.contains('assistant-message')) {
        lastMessage.innerHTML = marked.parse(text);
    } else {
        addMessage(text, 'assistant');
    }
    messages.scrollTop = messages.scrollHeight;
}

// 发送消息
async function sendMessage() {
    const input = document.getElementById('chat-input');
    const message = input.value.trim();
    
    if (!message) return;
    
    const kbId = document.getElementById('chat-kb-select').value;
    if (!kbId) {
        alert('请先选择知识库');
        return;
    }
    
    // 清空输入框
    input.value = '';
    
    // 添加用户消息到界面
    addMessage(message, 'user');
    
    // 获取选中的模型和系统提示词
    const model = document.getElementById('chat-model').value;
    const systemPrompt = document.getElementById('system-prompt').value;
    
    try {
        // 将消息添加到历史记录
        chatHistory.push({
            role: 'user',
            content: message
        });
        
        // 创建 AbortController 用于取消请求
        currentController = new AbortController();
        
        // 发送请求
        const response = await fetch(`${API_BASE}/chat/${kbId}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                query: message,
                model: model,
                system_prompt: systemPrompt,
                history: chatHistory
            }),
            signal: currentController.signal
        });

        if (!response.ok) {
            throw new Error('对话服务暂时不可用，请稍后重试');
        }

        const reader = response.body.getReader();
        let assistantMessage = '';

        while (true) {
            const {value, done} = await reader.read();
            if (done) break;
            
            const text = new TextDecoder().decode(value);
            const lines = text.split('\n').filter(line => line.trim());
            
            for (const line of lines) {
                if (line.startsWith('data: ')) {
                    try {
                        const jsonStr = line.slice(5).trim();
                        const data = JSON.parse(jsonStr);
                        
                        if (data.error) {
                            throw new Error(data.error);
                        }
                        
                        if (data.text) {
                            assistantMessage += data.text;
                            updateLastMessage(assistantMessage);
                        }
                    } catch (e) {
                        console.error('Error parsing SSE message:', e);
                        continue;
                    }
                }
            }
        }

        // 将助手回复添加到历史记录
        if (assistantMessage) {
            chatHistory.push({
                role: 'assistant',
                content: assistantMessage
            });
        }

    } catch (error) {
        if (error.name === 'AbortError') {
            addMessage('对话已停止', 'system');
        } else {
            console.error('Chat error:', error);
            addMessage(error.message || '发送消息失败', 'error');
        }
    } finally {
        currentController = null;
    }
}

// 停止对话
function stopChat() {
    if (currentController) {
        currentController.abort();
        addMessage('对话已停止', 'system');
    }
}

// 重置对话
function resetChat() {
    // 清空消息列表
    const messages = document.getElementById('chat-messages');
    messages.innerHTML = `
        <div class="text-center text-gray-500 my-4">
            <svg class="w-8 h-8 mx-auto mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                    d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
            </svg>
            <p>对话已重置，请开始新的对话</p>
        </div>
    `;
    
    // 停止当前对话（如果有）
    if (currentController) {
        currentController.abort();
        currentController = null;
    }
    
    // 重置对话状态
    chatHistory = [];
    
    // 调用后端重置接口
    fetch(`${API_BASE}/chat/reset`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.status !== 'success') {
            console.error('Reset chat error:', data.message);
        }
    })
    .catch(error => {
        console.error('Reset chat error:', error);
    });
    
    // 显示提示消息
    showMessage('对话已重置', 'info');
}

// 知识库管理相关函数
async function loadKnowledgeBases() {
    try {
        setLoading(true);
        const response = await fetch(`${API_BASE}/knowledge-base`);
        const data = await response.json();
        
        if (data.status !== 'success') {
            throw new Error(data.message || '加载知识库列表失败');
        }
        
        // 更新知识库列表
        const kbList = document.getElementById('kb-list');
        const items = data.data?.items || [];
        
        if (items.length === 0) {
            kbList.innerHTML = `
                <div class="text-center text-gray-500 py-4">
                    暂无知识库，请先创建
                </div>
            `;
        } else {
            kbList.innerHTML = items.map(kb => `
                <div class="border p-4 rounded hover:shadow-md transition-shadow">
                    <div class="flex justify-between items-start mb-2">
                        <h3 class="font-bold text-lg">${kb.name}</h3>
                        <span class="text-sm text-gray-500">ID: ${kb.id}</span>
                    </div>
                    <p class="text-gray-600 mb-3">${kb.description || '暂无描述'}</p>
                    <div class="flex justify-between items-center text-sm text-gray-500">
                        <div>
                            <span class="mr-4">文档数量: ${kb.document_count || 0}</span>
                            <span>模型: ${kb.embedding_model}</span>
                        </div>
                        <div>
                            <span>创建时间: ${new Date(kb.created_at).toLocaleString()}</span>
                        </div>
                    </div>
                </div>
            `).join('');
        }

        // 更新所有知识库选择框
        updateKnowledgeBaseSelects(items);
    } catch (error) {
        console.error('API Error:', error);
        showMessage(error.message || '加载知识库列表失败，请稍后重试', 'error');
    } finally {
        setLoading(false);
    }
}

// 更新知识库选择框
function updateKnowledgeBaseSelects(knowledgeBases) {
    const selects = ['kb-select', 'chat-kb-select'];
    selects.forEach(id => {
        const select = document.getElementById(id);
        if (!select) return;

        const currentValue = select.value;
        select.innerHTML = `
            <option value="" disabled ${!currentValue ? 'selected' : ''}>请选择知识库</option>
            ${knowledgeBases.map(kb =>
                `<option value="${kb.id}" ${kb.id.toString() === currentValue ? 'selected' : ''}>
                    ${kb.name} (${kb.document_count || 0}文档)
                </option>`
            ).join('')}
        `;

        // 触发 change 事件以更新相关控件状态
        select.dispatchEvent(new Event('change'));
    });
}

// 显示文件格式说明
async function showFormatHelp() {
    try {
        const response = await fetch(`${API_BASE}/document/template`);
        const data = await response.json();
        
        if (data.status !== 'success') {
            throw new Error(data.message || '获取格式说明失败');
        }

        const templates = data.data;
        const helpDialog = document.createElement('div');
        helpDialog.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';
        helpDialog.innerHTML = `
            <div class="bg-white rounded-lg shadow-xl p-6 max-w-2xl w-full mx-4">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-lg font-bold">文件格式说明</h3>
                    <button onclick="this.closest('.fixed').remove()" class="text-gray-500 hover:text-gray-700">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                        </svg>
                    </button>
                </div>
                <div class="space-y-4">
                    <div>
                        <h4 class="font-medium mb-2">CSV文件格式要求：</h4>
                        <pre class="bg-gray-50 p-3 rounded text-sm">${templates.csv.format}</pre>
                        <p class="mt-2 text-sm text-gray-600">示例：</p>
                        <pre class="bg-gray-50 p-3 rounded text-sm">${templates.csv.example}</pre>
                    </div>
                    <div>
                        <h4 class="font-medium mb-2">Excel文件格式要求：</h4>
                        <pre class="bg-gray-50 p-3 rounded text-sm">${templates.excel.format}</pre>
                    </div>
                    <p class="text-sm text-gray-500 mt-4">
                        注意：请确保文件编码为UTF-8格式，以避免中文乱码问题。
                    </p>
                </div>
            </div>
        `;
        
        document.body.appendChild(helpDialog);
    } catch (error) {
        console.error('Error:', error);
        showMessage(error.message || '获取格式说明失败，请稍后重试', 'error');
    }
}

// 显示消息提示
function showMessage(message, type = 'info') {
    const colors = {
        success: 'bg-green-50 text-green-800 border-green-200',
        error: 'bg-red-50 text-red-800 border-red-200',
        info: 'bg-blue-50 text-blue-800 border-blue-200'
    };
    
    const toast = document.createElement('div');
    toast.className = `fixed bottom-6 right-6 z-50 rounded-lg shadow-lg border p-4 transition-all transform duration-300 translate-y-full ${colors[type]}`;
    toast.innerHTML = `<div class="text-sm font-medium">${message}</div>`;
    
    document.body.appendChild(toast);
    
    requestAnimationFrame(() => {
        toast.classList.remove('translate-y-full');
    });
    
    setTimeout(() => {
        toast.classList.add('opacity-0', 'translate-y-2');
        setTimeout(() => toast.remove(), 300);
    }, 3000);
}

// 设置加载状态
function setLoading(isLoading) {
    const buttons = document.querySelectorAll('button');
    buttons.forEach(button => {
        if (!button.classList.contains('close-btn')) {
            button.disabled = isLoading;
            button.classList.toggle('opacity-50', isLoading);
        }
    });
}

// 创建知识库
async function createKnowledgeBase() {
    const name = document.getElementById('kb-name').value.trim();
    const description = document.getElementById('kb-desc').value.trim();
    const embeddingModel = document.getElementById('embedding-model').value;

    if (!name) {
        showMessage('请输入知识库名称', 'error');
        return;
    }

    try {
        setLoading(true);
        const response = await fetch(`${API_BASE}/knowledge-base`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                name,
                description,
                embedding_model: embeddingModel
            })
        });
        
        const data = await response.json();
        if (data.status !== 'success') {
            throw new Error(data.message || '创建知识库失败');
        }

        // 清空输入
        document.getElementById('kb-name').value = '';
        document.getElementById('kb-desc').value = '';

        // 重新加载知识库列表
        await loadKnowledgeBases();
        
        showMessage('知识库创建成功！', 'success');
    } catch (error) {
        console.error('Error:', error);
        showMessage(error.message || '创建知识库失败，请稍后重试', 'error');
    } finally {
        setLoading(false);
    }
}

// 加载系统提示词
async function loadSystemPrompts() {
    try {
        const response = await fetch(`${API_BASE}/system-prompt`);
        const data = await response.json();
        
        if (data.status !== 'success') {
            throw new Error(data.message || '加载系统提示词失败');
        }

        const select = document.getElementById('system-prompt');
        if (!select) return;

        const items = data.data?.items || [];
        select.innerHTML = `
            <option value="">默认系统提示词</option>
            ${items.map(prompt => `
                <option value="${prompt.id}">${prompt.name}</option>
            `).join('')}
        `;
    } catch (error) {
        console.error('Error loading system prompts:', error);
        showMessage('加载系统提示词失败', 'error');
    }
}

// 更新控件状态
function updateControlsState(hasKnowledgeBases) {
    const uploadBtn = document.getElementById('upload-btn');
    const chatInput = document.getElementById('chat-input');
    const chatBtn = document.getElementById('chat-btn');
    const kbSelect = document.getElementById('kb-select');
    const chatKbSelect = document.getElementById('chat-kb-select');
    
    // 更新上传按钮状态
    if (uploadBtn && kbSelect) {
        uploadBtn.disabled = !hasKnowledgeBases || !kbSelect.value;
    }
    
    // 更新聊天输入框和按钮状态
    if (chatInput && chatKbSelect) {
        chatInput.disabled = !hasKnowledgeBases || !chatKbSelect.value;
        if (chatBtn) {
            chatBtn.disabled = chatInput.disabled;
        }
    }
}

// 刷新知识库列表
async function refreshKnowledgeBases() {
    try {
        const refreshBtn = document.querySelector('button[onclick="refreshKnowledgeBases()"]');
        if (refreshBtn) {
            refreshBtn.disabled = true;
            refreshBtn.innerHTML = `
                <svg class="animate-spin -ml-1 mr-2 h-4 w-4 text-white inline-block" fill="none" viewBox="0 0 24 24">
                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                刷新中...
            `;
        }

        await loadKnowledgeBases();
        
        if (refreshBtn) {
            refreshBtn.disabled = false;
            refreshBtn.textContent = '刷新列表';
        }
    } catch (error) {
        console.error('Error refreshing knowledge bases:', error);
        showMessage('刷新知识库列表失败: ' + error.message, 'error');
        
        const refreshBtn = document.querySelector('button[onclick="refreshKnowledgeBases()"]');
        if (refreshBtn) {
            refreshBtn.disabled = false;
            refreshBtn.textContent = '刷新列表';
        }
    }
}

// 文件上传相关函数
async function uploadDocument() {
    const fileInput = document.getElementById('file-input');
    const kbSelect = document.getElementById('kb-select');
    const splitMethod = document.getElementById('split-method');
    const statusElement = document.getElementById('task-status');
    
    if (!fileInput.files.length) {
        showMessage('请选择要上传的文件', 'error');
        return;
    }
    
    if (!kbSelect.value) {
        showMessage('请选择知识库', 'error');
        return;
    }
    
    const file = fileInput.files[0];
    const formData = new FormData();
    formData.append('file', file);
    formData.append('split_method', splitMethod.value);
    
    // 更新状态显示
    statusElement.innerHTML = `
        <div class="flex items-center space-x-2 text-blue-600">
            <svg class="w-5 h-5 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                    d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
            </svg>
            <span>正在上传文件...</span>
        </div>
    `;
    
    try {
        // 禁用上传按钮
        const uploadBtn = document.getElementById('upload-btn');
        uploadBtn.disabled = true;
        
        // 开始上传
        const response = await fetch(`${API_BASE}/document/upload/${kbSelect.value}`, {
            method: 'POST',
            body: formData
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data = await response.json();
        if (data.status !== 'success') {
            throw new Error(data.message || '上传失败');
        }
        
        // 获取任务ID并开始轮询任务状态
        const taskId = data.data.task_id;
        showMessage('文件上传成功，正在处理...', 'success');
        
        // 清空文件输入
        fileInput.value = '';
        document.getElementById('selected-file-name').textContent = '';
        
        // 开始轮询任务状态
        pollTaskStatus(taskId);
        
    } catch (error) {
        console.error('Upload error:', error);
        showMessage(error.message || '上传失败，请稍后重试', 'error');
        statusElement.innerHTML = `
            <div class="text-red-600">
                上传失败: ${error.message || '请稍后重试'}
            </div>
        `;
    } finally {
        // 重新启用上传按钮
        const uploadBtn = document.getElementById('upload-btn');
        uploadBtn.disabled = false;
    }
}

// 轮询任务状态
async function pollTaskStatus(taskId) {
    const statusElement = document.getElementById('task-status');
    if (!statusElement) return;
    
    try {
        while (true) {
            const response = await fetch(`${API_BASE}/task/${taskId}`);
            const data = await response.json();
            
            if (data.status !== 'success') {
                throw new Error(data.message || '获取任务状态失败');
            }
            
            const task = data.data;
            
            // 更新状态显示
            statusElement.innerHTML = `
                <div class="flex items-center space-x-2 ${
                    task.status === 'completed' ? 'text-green-600' :
                    task.status === 'failed' ? 'text-red-600' :
                    'text-blue-600'
                }">
                    ${
                        task.status === 'completed' ? 
                        '<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg>' :
                        task.status === 'failed' ?
                        '<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>' :
                        '<svg class="w-5 h-5 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/></svg>'
                    }
                    <span>${task.message || task.status}</span>
                    ${task.progress ? `<span class="text-sm text-gray-500">(${task.progress}%)</span>` : ''}
                </div>
            `;
            
            // 如果任务完成或失败，停止轮询
            if (task.status === 'completed' || task.status === 'failed') {
                if (task.status === 'completed') {
                    showMessage('文档处理完成！', 'success');
                    // 刷新知识库列表
                    await loadKnowledgeBases();
                } else {
                    showMessage(task.error || '文档处理失败', 'error');
                }
                break;
            }
            
            // 等待一段时间后继续轮询
            await new Promise(resolve => setTimeout(resolve, 1000));
        }
    } catch (error) {
        console.error('Error polling task status:', error);
        showMessage(error.message || '获取任务状态失败', 'error');
    }
}

// 文件选择处理
function handleFileSelect(event) {
    const file = event.target.files[0];
    if (!file) return;
    
    const fileNameElement = document.getElementById('selected-file-name');
    if (fileNameElement) {
        fileNameElement.textContent = file.name;
    }
    
    // 根据文件类型自动选择分割方法
    const splitMethod = document.getElementById('split-method');
    if (splitMethod) {
        const ext = file.name.split('.').pop().toLowerCase();
        if (ext === 'csv' || ext === 'xlsx' || ext === 'xls') {
            splitMethod.value = 'raw';  // 结构化文件默认使用原始格式
        } else {
            splitMethod.value = 'char';  // 文本文件默认使用字符分割
        }
    }
}

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', () => {
    loadKnowledgeBases();
    loadSystemPrompts();
    
    // 添加知识库选择框变更事件监听
    const kbSelect = document.getElementById('kb-select');
    if (kbSelect) {
        kbSelect.addEventListener('change', () => {
            updateControlsState(true);
        });
    }
    
    // 添加对话知识库选择框变更事件监听
    const chatKbSelect = document.getElementById('chat-kb-select');
    if (chatKbSelect) {
        chatKbSelect.addEventListener('change', () => {
            const chatInput = document.getElementById('chat-input');
            const chatBtn = document.getElementById('chat-btn');
            if (chatInput && chatBtn) {
                const isDisabled = !chatKbSelect.value;
                chatInput.disabled = isDisabled;
                chatBtn.disabled = isDisabled;
            }
        });
    }
    
    // 添加回车发送功能
    const chatInput = document.getElementById('chat-input');
    if (chatInput) {
        chatInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });
    }
    
    // 添加系统提示词变更事件监听
    const systemPromptSelect = document.getElementById('system-prompt');
    if (systemPromptSelect) {
        systemPromptSelect.addEventListener('change', () => {
            // 如果正在进行对话，提示用户
            if (chatHistory.length > 0) {
                if (confirm('更换系统提示词将重置当前对话，是否继续？')) {
                    resetChat();
                } else {
                    // 恢复之前的选择
                    systemPromptSelect.value = chatHistory.find(msg => msg.role === 'system')?.content || '';
                }
            }
        });
    }
    
    // 添加文件选择事件监听
    const fileInput = document.getElementById('file-input');
    if (fileInput) {
        fileInput.addEventListener('change', handleFileSelect);
    }
}); 